import tkinter as tk

from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import random
import string
import csv
import os
from datetime import datetime
 
def Main_menu():
    return ""

def config_info():
    return ""
# 生成16位随机表头编号，最后两位为随机16进制码
def generate_header_id():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=14)) + ''.join(random.choices('0123456789abcdef', k=2))

# 生成12位随机档案编号
def generate_archive_id():
    return ''.join(random.choices(string.digits, k=12))

# 保存信息到CSV文件
csv_file_path = 'volunteers.csv'
def save_to_csv(data):
    if not os.path.exists(csv_file_path):
        with open(csv_file_path, 'w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(['档案编号', '姓名', '班级', '身份证', '年龄', '性别','手机号','邮箱'] + [f'表头编号{i+1}' for i in range(5)])
    with open(csv_file_path, 'a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(data)
        
# 从身份证搜索年龄
def calculate_age(id_card):
    try:
        birth_date_str = id_card[6:14]
        # 验证日期字符串是否仅包含数字
        if not birth_date_str.isdigit():
            raise ValueError("身份证中的出生日期部分包含非数字字符")
        birth_date = datetime.strptime(birth_date_str, '%Y%m%d').date()
        today = datetime.today().date()
        age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
        return str(age)
    except ValueError as e:
        # 如果解析日期时发生错误，返回错误消息或适当的默认值
        messagebox.showerror("错误", f"无法解析出生日期: {e}")
        return ""  # 或者返回一个默认值，如 "未知"
def search_record():
    search_text = search_entry.get()
    if not search_text:
        messagebox.showwarning("警告", "请输入搜索内容")
        return
    
    with open(csv_file_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        headers = next(reader)  # 跳过标题行
        search_results = []
        for row in reader:
            if search_text in row:
                search_results.append(row)
    
    if search_results:
        for result in search_results:
            show_search_result(result)
    else:
        messagebox.showwarning("警告", "未找到匹配记录")
 
# 显示搜索结果的函数
def show_search_result(result):
    result_text = (
        f"档案编号：{result[0]}\n"
        f"姓名：{result[1]}\n"
        f"班级：{result[2]}\n"
        f"身份证：******{result[3][-4:]}\n"
        f"年龄：{result[4]}\n"
        f"性别：{result[6]}\n"
        f"手机号：{result[7]}\n"
        f"邮箱：{result[5]}\n"
    )
    # 确保不会访问超出范围的索引
    for i in range(8, min(13, len(result))):  # 修改这里
        result_text += f"表头编号{i-7}:{result[i]}\n"
    messagebox.showinfo("搜索结果", result_text)

# 创建并验证输入页面
def validate_and_submit():
    name = name_entry.get()
    class_name = class_entry.get()
    id_card = id_entry.get()
    age = calculate_age(id_card)
    # age_entry.delete(0, tk.END)
    # age_entry.insert(0, age)  # 不再需要这行代码
    gender = gender_entry.get()
    phone_number = phone_number_entry.get()
    mail = mail_entry.get()
 
    if not all([name, class_name, id_card, gender]):
        missing_fields = [field for field, value in zip(['姓名', '班级', '身份证', '性别','手机号','邮箱'], [name, class_name, id_card, gender,phone_number,mail]) if not value]
        messagebox.showerror("错误", f"请填写以下字段: {', '.join(missing_fields)}")
        return
 
    # 重复检测逻辑
    with open(csv_file_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过标题行
        for row in reader:
            if id_card == row[3]:  # 假设身份证是唯一标识符
                messagebox.showerror("错误", "档案已存在，请检查！")
                return
 
    archive_id = generate_archive_id()
    header_ids = [generate_header_id() for _ in range(5)]
    data = [archive_id, name, class_name, id_card, age, gender,phone_number,mail] + header_ids
    save_to_csv(data)
    messagebox.showinfo("成功", "档案创建成功！")
     # 清空输入框
    for widget in [name_entry, class_entry, id_entry, gender_entry,phone_number_entry,mail_entry]:
        widget.delete(0, tk.END)

# 创建输入页面组件
def create_input_frame(frame):
    tk.Label(frame, text="姓名:").grid(row=0, column=0, padx=20, pady=10)
    name_entry = tk.Entry(frame)
    name_entry.grid(row=0, column=1, padx=10, pady=10)
 
    tk.Label(frame, text="班级:").grid(row=1, column=0, padx=20, pady=10)
    class_entry = tk.Entry(frame)
    class_entry.grid(row=1, column=1, padx=10, pady=10)
 
    tk.Label(frame, text="身份证:").grid(row=2, column=0, padx=20, pady=10)
    id_entry = tk.Entry(frame, show="*")
    id_entry.grid(row=2, column=1, padx=10, pady=10)
    
 
    # tk.Label(frame, text="年龄:").grid(row=3, column=0, padx=10, pady=10)
    # age_entry = tk.Entry(frame)
    # age_entry.grid(row=3, column=1, padx=10, pady=10)
 
    gender_label = tk.Label(frame, text="性别:")
    gender_label.grid(row=3, column=0, padx=20, pady=10)
    gender_values = ['男', '女']
    gender_combobox = ttk.Combobox(frame, values=gender_values, state='readonly',width=17)
    gender_combobox.grid(row=3, column=1, padx=10, pady=10)
    gender_combobox.current(0)  # 默认选择第一个选项
    
    tk.Label(frame, text="手机号:").grid(row=4, column=0, padx=20, pady=10)
    phone_number_entry = tk.Entry(frame)
    phone_number_entry.grid(row=4, column=1, padx=10, pady=10)

    tk.Label(frame, text="邮箱用户名:").grid(row=5, column=0, padx=20, pady=10)
    mail_username_entry = tk.Entry(frame)
    mail_username_entry.grid(row=5, column=1, padx=10, pady=10, columnspan=1)  # Adjust columnspan if needed
 
    
    mail_domain_options = ['@163.com', '@qq.com', '@126.com']  # Example domains
    mail_domain_combobox = ttk.Combobox(frame, values=mail_domain_options, state='readonly',width=10)
    mail_domain_combobox.grid(row=5, column=3, padx=10, pady=10)
    mail_domain_combobox.current(0)  # Default to first option
    username = mail_username_entry.get()
    domain = mail_domain_combobox.get()
    mail_entry = f"{username}{domain}"

    tk.Button(frame, text="创建档案", command=validate_and_submit,width=30).grid(row=6, column=0, columnspan=2, padx=50,pady=20)
 
    return name_entry, class_entry, id_entry, gender_combobox,phone_number_entry,mail_entry  # 注意这里移除了 age_entry
 

# 创建查询页面组件
def create_search_frame(frame):
    tk.Label(frame, font=("黑体",16 ),text="查询档案").grid(column=0)
    
    tk.Label(frame,font=("黑体",14 ), text="搜索内容:").grid(row=1, column=0, padx=5, pady=70)
    search_entry = tk.Entry(frame, width=30)
    search_entry.grid(row=1, column=1, padx=20, pady=10,ipady=5)

    tk.Button(frame,font=("黑体",12 ), text="搜索", command=search_record, width=40).grid(row=2, column=0, columnspan=2, padx=100,pady=20)
    
    return search_entry




























































































































# 创建和设置主窗口
root = tk.Tk()
root.title("志愿者管理系统")
root.geometry("500x500")
root.resizable(0, 0)
root.iconphoto(False, tk.PhotoImage(file='icon.png'))
# 创建两个框架（页面）
MainMenu = ttk.Frame(root)
frameA = ttk.Frame(root)
frameB = ttk.Frame(root)
frameC = ttk.Frame(root)

# 放置框架和按钮
MainMenu.grid(row=0, column=0, sticky="nsew")
frameA.grid_remove()
frameB.grid_remove()  # 隐藏frame2
frameC.grid_remove()  # 隐藏frame3

# 创建输入页面组件
name_entry, class_entry, id_entry, phone_number_entry ,mail_entry,  gender_entry = create_input_frame(frameA) 

# 创建查询页面组件
search_entry = create_search_frame(frameB)


# 定义切换页面的函数（这些函数已经正确）
def switch_to_MainMenu():
    frameA.grid_remove()
    frameB.grid_remove()
    frameC.grid_remove()
    MainMenu.grid(row=0, column=0, sticky="nsew")
    MainMenu.tkraise()

def switch_to_frameA():
    frameB.grid_remove()
    frameC.grid_remove()
    frameA.grid(row=0, column=0, sticky="nsew")
    frameA.tkraise()
 
def switch_to_frameB():
    frameA.grid_remove()
    frameC.grid_remove()
    frameB.grid(row=0, column=0, sticky="nsew")
    frameB.tkraise()
 
def switch_to_frameC():  
    
    frameA.grid_remove()
    frameB.grid_remove()
    messagebox.showerror("警告","未制作完成，返回主页")
    # frameC.grid(row=0, column=0, sticky="nsew")
    # frameC.tkraise()
   
 
# 创建按钮切换页面（这些按钮已经正确放置在各自的框架内）
def tk_MainMenu():
    tk.Label(MainMenu, font=("黑体",18 ),text="志愿者服务平台菜单").grid(row=0, column=0, padx=10, pady=10)
    
    button_frameB_to_frameA = ttk.Button(MainMenu,width=30, text=" 创 建 档 案 ", command=switch_to_frameA)
    button_frameB_to_frameA.grid(padx=135,pady=40,row=2,column=0)
    button_frameA_to_frameB = ttk.Button(MainMenu,width=30, text=" 查 询 档 案 ", command=switch_to_frameB)
    button_frameA_to_frameB.grid(padx=135,pady=40, row=3, column=0)
    button_frameA_to_frameC = ttk.Button(MainMenu,width=30, text=" 修 改 档 案 ", command=switch_to_frameC)  # 新增按钮
    button_frameA_to_frameC.grid(padx=135,pady=40, row=4, column=0)  # 放置在第二行
    switch_to_MainMenu()


def tk_frameA():
    button_frameA_to_frameB = ttk.Button(frameA, text="查询档案", command=switch_to_frameB)
    button_frameA_to_frameB.grid(pady=10, row=7, column=0)
    button_frameA_to_frameC = ttk.Button(frameA, text="修改档案", command=switch_to_frameC)  # 新增按钮
    button_frameA_to_frameC.grid(pady=10, row=8, column=0)  # 放置在第二行
    button_switch_to_MainMenu =ttk.Button(frameA, text="返回菜单", command=switch_to_MainMenu)
    button_switch_to_MainMenu.grid(pady=10, row=9, column=0)
def tk_frameB():
    button_frameB_to_frameA = ttk.Button(frameB, text="创建档案", command=switch_to_frameA)
    button_frameB_to_frameA.grid(pady=10,row=7,column=0)
    button_frameB_to_frameC = ttk.Button(frameB, text="修改档案", command=switch_to_frameC)
    button_frameB_to_frameC.grid(pady=10, row=8, column=0)  
    button_switch_to_MainMenu =ttk.Button(frameB, text="返回菜单", command=switch_to_MainMenu)
    button_switch_to_MainMenu.grid(pady=10, row=9, column=0)
def tk_frameC():
    button_frameC_to_frameA = ttk.Button(frameC, text="创建档案", command=switch_to_frameA)  # 假设从查询菜单可以创建档案
    button_frameC_to_frameA.grid(pady=20, row=7, column=0)
    button_frameC_to_frameB = ttk.Button(frameC, text="查询档案", command=switch_to_frameB)  # 假设从查询菜单可以修改档案（这里逻辑上可能不太合理，但仅作为示例）
    button_frameC_to_frameB.grid(pady=10, row=8, column=0)
    button_switch_to_MainMenu =ttk.Button(frameC, text="返回菜单", command=switch_to_MainMenu)
    button_switch_to_MainMenu.grid(pady=10, row=9, column=0)
tk_MainMenu()
tk_frameA()
tk_frameB()
tk_frameC()



 
def place_exit_button():
    # 计算按钮位置，确保它位于窗口右下角
    button_width = 60  # 设置按钮宽度（示例值）
    button_height = 20  # 设置按钮高度（示例值）
    x_pos = root.winfo_width() - button_width - 10  # 10是右边距
    y_pos = root.winfo_height() - button_height - 10  # 10是下边距
    exit_button.place(x=x_pos, y=y_pos, width=button_width, height=button_height)

def on_closing():
    if tk.messagebox.askokcancel("退出", "你确定要退出吗?"):
        root.destroy()
# 创建退出按钮，并绑定到退出函数
exit_button = tk.Button(root, text="退出", command=on_closing)
place_exit_button()
 
# 绑定窗口大小调整事件
root.bind("<Configure>", place_exit_button)

# 运行主循环
root.mainloop()